#include "IODeviceWithThreadSupport.h"


IODeviceWithThreadSupport::IODeviceWithThreadSupport(IODeviceType type, IODeviceContext* context)
	: IODeviceWithoutThreadSupport(type, context)
	, m_bFlag(true)
	, m_mutex()
{
	
}


IODeviceWithThreadSupport::~IODeviceWithThreadSupport()
{

}

void IODeviceWithThreadSupport::SendOperation(IODeviceOperation operation, unsigned int param)
{
	m_mutex.Lock();
	m_listOperation.push_back(std::pair<IODeviceOperation, unsigned int>(operation, param));
	m_mutex.UnLock();
}

bool IODeviceWithThreadSupport::GetOperation(IODeviceOperation& operation, unsigned int& param)
{
	if (m_listOperation.empty()) {
		operation = IO_OPERATION_INVALID;
		param = 0;
		return false;
	}
	else {
		m_mutex.Lock();
		operation = m_listOperation.begin()->first;
		param = m_listOperation.begin()->second;
		m_listOperation.pop_front();
		m_mutex.UnLock();
		return true;
	}
}

void IODeviceWithThreadSupport::OnOperation(IODeviceOperation operation, unsigned int param)
{

}

void* IODeviceWithThreadSupport::Run(void* data)
{
	IODeviceOperation operation;
	unsigned int param;
	while (m_bFlag) {
		if (GetOperation(operation, param)) {
			OnOperation(operation, param);
		}
	}
	return NULL;
}

void IODeviceWithThreadSupport::Start()
{
	m_bFlag = true;
	BDThread::Start();
}

void IODeviceWithThreadSupport::Stop()
{
	m_bFlag = false;
	BDThread::Wait();
}